#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define MAX_DATA  512
#define MAX_ROWS  512

struct Address {

    int id;
    int set;
    char name [MAX_DATA];
    char email[MAX_DATA];
};

struct Database {

    struct Address rows[MAX_ROWS];
};

struct Connection {
    FILE *file;
    struct Database *db;
};
void Database_close(struct Connection *conn)
{
    if(conn) {
        if(conn->file) fclose(conn->file);
        if(conn->db) free(conn->db);
        free(conn);
    }
}
void die(const char *message ,struct Connection *conn)
{
    if(errno) {
        perror(message);
    } else {
        printf("ERROR: %s\n", message);
    }
    Database_close(conn); // free

    exit(1);
}

void Address_print(struct Address *addr)
{
    printf("%d %s %s\n",
            addr->id, addr->name, addr->email);
}

void Database_load(struct Connection *conn)
{
    int rc = fread(conn->db, sizeof(struct Database), 1, conn->file);
    // fread：将conn->file文件流的内容以Database为大小向conn->db输入一次
    if(rc != 1) die("Failed to load database.",conn);
}

struct Connection *Database_open(const char *filename, char mode)
{
    struct Connection *conn = malloc(sizeof(struct Connection));
    if(!conn) die("Memory error",conn);

    conn->db = malloc(sizeof(struct Database));
    if(!conn->db) die("Memory error",conn);

    if(mode == 'c') {
        conn->file = fopen(filename, "w");
    } else {
        conn->file = fopen(filename, "r+");

        if(conn->file) {
            Database_load(conn);
        }
    }

    if(!conn->file) die("Failed to open the file",conn);

    return conn;
}



void Database_write(struct Connection *conn)
{
    rewind(conn->file);
    //将文件指针移动到文件开头，等同于fseek（stream，0L，SEEK_SET）；

    int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
    // fwrite：将conn->db的内容以Database为大小输出到 conn->file
    if(rc != 1) die("Failed to write database.",conn);

    rc = fflush(conn->file);
    //刷新标准输出缓冲区，把输出缓冲区里的东西打印到标准输出设备上
    if(rc == -1) die("Cannot flush database.",conn);
}

void Database_create(struct Connection *conn)
{
    int i = 0;

    for(i = 0; i < MAX_ROWS; i++) {
        // make a prototype to initialize it
        struct Address addr = {.id = i, .set = 0};
        // then just assign it
        conn->db->rows[i] = addr;
    //临时局部Address变量，初始化id和set字段(其他为0)，把它赋值给rows数组中的元素，结构体可直接复制
    }
}

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
    struct Address *addr = &conn->db->rows[id];
//    if(conn->db->rows[id].set) die("Already set, delete it first",conn);
    if(addr->set) die("Already set, delete it first",conn);
    addr->set = 1;
    // WARNING: bug, read the "How To Break It" and fix this
    char *res = strncpy(addr->name, name,MAX_DATA);
    addr->name[MAX_DATA-1] = '\0'; // FIX BUG
    // demonstrate the strncpy bug
    if(!res) die("Name copy failed",conn);

    res = strncpy(addr->email, email,MAX_DATA);
    addr->email[MAX_DATA-1] = '\0';
    if(!res) die("Email copy failed",conn);
}

void Database_get(struct Connection *conn, int id)
{
    struct Address *addr = &conn->db->rows[id];

    if(addr->set) {
        Address_print(addr);
    } else {
        die("ID is not set",conn);
    }
}

void Database_find(struct Connection *conn, const char *str)
{
    int i=0;
    for(i=0;i<MAX_ROWS;i++)
    {
        struct Address *addr = &conn->db->rows[i];
        if((addr->set == 1) && (strstr(addr->name,str) || strstr(addr->email,str) ) )
        {
            Address_print(addr);
            break;
        }
    }
    if(i == MAX_ROWS)
        printf("NOT EXIST!\n");    
}

void Database_delete(struct Connection *conn, int id)
{
    struct Address addr = {.id = id, .set = 0};
    conn->db->rows[id] = addr;
}

void Database_list(struct Connection *conn)
{
    int i = 0;
    struct Database *db = conn->db;

    for(i = 0; i < MAX_ROWS; i++) {
        struct Address *cur = &db->rows[i];

        if(cur->set) {
            Address_print(cur);
        }
    }
}

int main(int argc, char *argv[])
{
//    int MAX_data;
//    int MAX_rows;
    char *filename = argv[1];
    char action    = argv[2][0];
    // struct Address A;
    // struct Database B;
    // struct Connection C;
    // printf("Address: %ld,Database: %ld,Connection:%ld\n",sizeof(A),sizeof(B),sizeof(C));
    // if(action == 'c');
    // {
    //     int  MAX_data  = atoi(argv[3]) ;
    //     int  MAX_rows  = atoi(argv[4]) ;   // 可变rows，data   
    // }
    struct Connection *conn = Database_open(filename, action);



    int id = 0;
    if(argc < 3) die("USAGE: ex17 <dbfile> <action> [action params]",conn);
    if(argc > 3) id = atoi(argv[3]);//将字符串转化为int
    if(id >= MAX_ROWS) die("There's not that many records.",conn);

    switch(action) {
        case 'c':

            Database_create(conn);
            Database_write(conn);
            break;

        case 'g':
            if(argc != 4) die("Need an id to get",conn);

            Database_get(conn, id);
            break;

        case 's':
            if(argc != 6) die("Need id, name, email to set",conn);

            Database_set(conn, id, argv[4], argv[5]);
            Database_write(conn);
            break;

        case 'd':
            if(argc != 4) die("Need id to delete",conn);

            Database_delete(conn, id);
            Database_write(conn);
            break;

        case 'l':
            Database_list(conn);
            break;

        case 'f':
            Database_find(conn,argv[3]);  
            break;          
        default:
            die("Invalid action, only: c=create, g=get, s=set, d=del, l=list, find=f",conn);
    }

   // Database_close(conn);

    return 0;
}